<?php

namespace App\Containers\AppSection\Confirmation\Tasks;

use App\Containers\AppSection\Confirmation\Data\Repositories\ConfirmationRepository;
use App\Containers\AppSection\Confirmation\Exceptions\ConfirmationBadRequestException;
use App\Containers\AppSection\Confirmation\Models\Confirmation;
use App\Ship\Parents\Tasks\Task;
use Carbon\Carbon;

class FindConfirmationByCodeTask extends Task
{
    protected ConfirmationRepository $repository;

    public function __construct(ConfirmationRepository $repository)
    {
        $this->repository = $repository;
        //
    }

    public function run(
        string $code,
        string $value,
        string $requestType,
        string $confirmType
    ): ?Confirmation
    {
        $confirm = $this->repository->findWhere([
            ['code', '=', $code],
            ['value', '=', $value],
            ['request_type', '=', $requestType],
            ['confirm_type', '=', $confirmType],
        ])->first();

        if (empty($confirm) ||
            $confirm->getCreatedAtColumn() <= Carbon::now()->subSeconds(config('appSection-confirmation.expires-in'))) {
            throw new ConfirmationBadRequestException(__('appSection@confirmation::code.wrong'));
        }

        return $confirm;
    }
}
